package net.hn.hnms.biz.plan.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import net.hn.hnms.biz.plan.domain.PlanTunnelRepair;
import net.hn.hnms.biz.plan.domain.PlanWashing;
import net.hn.hnms.biz.plan.mapper.PlanTunnelRepairMapper;
import net.hn.hnms.biz.plan.request.PlanTunnelRepairReq;
import net.hn.hnms.biz.plan.service.PlanTunnelRepairService;
import net.hn.hnms.biz.plan.vo.PlanTunnelRepairVo;
import net.hn.hnms.sys.common.core.constant.Constants;
import net.hn.hnms.sys.common.core.domain.ResponsePage;
import net.hn.hnms.sys.common.core.exception.HuaNengException;
import net.hn.hnms.sys.common.mybatis.core.page.PageQuery;
import net.hn.hnms.sys.system.api.RemoteUserService;
import net.hn.hnms.sys.system.api.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
@DS("master")
public class PlanTunnelRepairServiceImpl extends BaseService<PlanTunnelRepair, PlanTunnelRepairVo> implements PlanTunnelRepairService {


    @Resource
    private PlanTunnelRepairMapper planTunnelRepairMapper;
    @Autowired
    private RemoteUserService remoteUserService;

    @Override
    public ResponsePage<PlanTunnelRepairVo> selectPageList(PlanTunnelRepairReq tunnelRepair, PageQuery pageQuery) {

        Page<PlanTunnelRepair> page = planTunnelRepairMapper.selectPage(pageQuery.build(), buildQuery(tunnelRepair).orderByDesc(PlanTunnelRepair::getRepairPlanCode).orderByDesc(PlanTunnelRepair::getCreateTime));
        List<PlanTunnelRepairVo> list = page.getRecords().stream().map(o -> convert(o, PlanTunnelRepairVo.class,o.getRepairPlanType())).collect(Collectors.toList());
        list.forEach(ii->{
            LoginUser userInfoById = remoteUserService.getUserInfoById(Long.valueOf(ii.getCreateUserId()));
            if (Optional.ofNullable(userInfoById).isPresent()) {
                ii.setCreateUserName(userInfoById.getNickname());
            }

        });
        return new ResponsePage<>(list, page.getTotal());
    }

    @Override
    public List<PlanTunnelRepairVo> selectList(PlanTunnelRepairReq planMining) {
        List<PlanTunnelRepair> list = planTunnelRepairMapper.selectList(buildQuery(planMining));
        return list.stream().map(o -> convert(o, PlanTunnelRepairVo.class, o.getRepairPlanType())).collect(Collectors.toList());
    }

    @Override
    public int insert(PlanTunnelRepairReq planMining) {
        PlanTunnelRepair insertObj = new PlanTunnelRepair();
        copyProperties(planMining, insertObj, planMining.getRepairPlanType());
        //自动生成 计划名称 计划编号
        if(planMining.getRepairPlanType().equals("3")){
//            insertObj.setRepairPlanName(generatePlanName(planMining.getRepairPlanType(),insertObj.getWeekTimeStart()));
//            insertObj.setDrivagePlanCode(generatePlanCode(planMining.getRepairPlanType(),insertObj.getWeekTimeStart()));
//            insertObj.setPlanStartDate(insertObj.getWeekTimeStart());
//            insertObj.setPlanEndDate(insertObj.getWeekTimeEnd());
        }else{
            insertObj.setRepairPlanName(generatePlanName(planMining.getRepairPlanType(),insertObj.getPlanStartDate()));
            insertObj.setRepairPlanCode(generatePlanCode(planMining.getRepairPlanType(),insertObj.getPlanStartDate()));
        }
        insertObj.setStatus("0");
        QueryWrapper<PlanTunnelRepair> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("repair_plan_code", insertObj.getRepairPlanCode());
        queryWrapper.eq("repair_plan_id", insertObj.getRepairPlanId());
        if (planTunnelRepairMapper.selectCount(queryWrapper) > 0) {
            throw new HuaNengException(Constants.FAIL, "已存在同一时段的计划");
        }
        return planTunnelRepairMapper.insert(insertObj);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(List<String> idList) {
        planTunnelRepairMapper.deleteBatchIds(idList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateById(PlanTunnelRepairReq planMining) {
//        if (StrUtil.isBlank(planMining.getRepairPlanId())){
//            throw new HuaNengException(Constants.FAIL, "id不能为空");
//        }
//        PlanTunnelRepair updateObj = new PlanTunnelRepair();
//        copyProperties(planMining, updateObj, planMining.getRepairPlanType(),"planStartDate","planEndDate");
//        updateObj.setRepairPlanName(generatePlanName(planMining.getRepairPlanType(),updateObj.getPlanStartDate()));
//        updateObj.setRepairPlanCode(generatePlanCode(planMining.getRepairPlanType(),updateObj.getPlanStartDate()));
//        QueryWrapper<PlanTunnelRepair> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("repair_plan_code", updateObj.getRepairPlanCode());
//        queryWrapper.ne("repair_plan_id", updateObj.getRepairPlanId());
////        queryWrapper.eq("repair_plan_id", updateObj.getDrivageFaceId());
//        if (planTunnelRepairMapper.selectCount(queryWrapper) > 0) {
//            throw new HuaNengException(Constants.FAIL, "已存在同一时段的计划");
//        }
//        int updateCount = planTunnelRepairMapper.updateById(updateObj);
//        if (updateCount == 0) {
//            throw new HuaNengException(Constants.FAIL, "数据不存在");
//        }


        if (StrUtil.isBlank(planMining.getRepairPlanId())) {
            throw new HuaNengException(Constants.FAIL, "id不能为空");
        }
        PlanTunnelRepair updateObj = new PlanTunnelRepair();
        copyProperties(planMining, updateObj, planMining.getRepairPlanType(),"planStartDate","planEndDate");
        updateObj.setRepairPlanName(generatePlanName(planMining.getRepairPlanType(),updateObj.getPlanStartDate()));
        updateObj.setRepairPlanCode(generatePlanCode(planMining.getRepairPlanType(),updateObj.getPlanStartDate()));
        QueryWrapper<PlanTunnelRepair> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("repair_plan_code", updateObj.getRepairPlanCode());
        queryWrapper.ne("repair_plan_id", updateObj.getRepairPlanId());
        if (planTunnelRepairMapper.selectCount(queryWrapper) > 0) {
            throw new HuaNengException(Constants.FAIL, "已存在同一时段的计划");
        }
        int updateCount = planTunnelRepairMapper.updateById(updateObj);
        if (updateCount == 0) {
            throw new HuaNengException(Constants.FAIL, "数据不存在");
        }
    }

    @Override
    public PlanTunnelRepairVo selectDetailById(String id) {
        PlanTunnelRepair planDrivage = planTunnelRepairMapper.selectById(id);
        if (planDrivage == null) {
            throw new HuaNengException(Constants.FAIL, "数据不存在");
        }
        return convertWithUser(planDrivage, PlanTunnelRepairVo.class);
    }

    @Override
    public void changeStatus(String id, Integer status) {
        if (status == 1 || status == 0) {
            PlanTunnelRepair planMining = planTunnelRepairMapper.selectById(id);
            if (planMining == null) {
                throw new HuaNengException(Constants.FAIL, "数据不存在");
            }
            planMining.setStatus(status + "");
            int res = planTunnelRepairMapper.updateById(planMining);
            if (res == 0) {
                throw new HuaNengException(Constants.FAIL, "数据不存在");
            }

            return;
        }
        throw new HuaNengException(Constants.FAIL, "传入的参数错误");
    }


    /**
     * 构造查询条件
     * @param req
     * @return LambdaQueryWrapper<PlanDevelopment> 查询条件
     */
    private LambdaQueryWrapper<PlanTunnelRepair> buildQuery(PlanTunnelRepairReq req){
        LambdaQueryWrapper<PlanTunnelRepair> lqw = new LambdaQueryWrapper<PlanTunnelRepair>()
                .like(StrUtil.isNotBlank(req.getRepairPlanCode()), PlanTunnelRepair::getRepairPlanCode, req.getRepairPlanCode())
                .like(StrUtil.isNotBlank(req.getRepairPlanName()), PlanTunnelRepair::getRepairPlanName, req.getRepairPlanName())
                .like(StrUtil.isNotBlank(req.getResponsibleUser()), PlanTunnelRepair::getResponsibleUser, req.getResponsibleUser())
                .eq(StrUtil.isNotBlank(req.getRepairPlanType()), PlanTunnelRepair::getRepairPlanType, req.getRepairPlanType())
                .eq(StrUtil.isNotBlank(req.getMineCode()), PlanTunnelRepair::getMineCode, req.getMineCode())
                .eq(StrUtil.isNotBlank(req.getStatus()), PlanTunnelRepair::getStatus, req.getStatus())
                .and(o->o.eq(req.getMineCode()!=null, PlanTunnelRepair::getMineCode, req.getMineCode()).or().eq(req.getCompanyCode()!=null, PlanTunnelRepair::getCompanyCode, req.getCompanyCode()));

        return lqw;
    }
}
